//
//  MBPhotoManagerView.m
//  Meboo
//
//  Created by kyo on 2024/3/8.
//

#import "MBPhotoManagerView.h"

#import "MBPhotoSelectViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "FirebaseCore/FirebaseCore.h"
#import "FirebaseStorage/FirebaseStorage-Swift.h"
#import "MBPhotoItemView.h"
#define wid (ScreenWidth-MBWidthScale(78))/3
@interface MBPhotoManagerView ()
@property(nonatomic,strong) UILabel *titleLab;

//震动
@property (nonatomic, strong) NSMutableArray *imageArr;

@property (nonatomic, strong) NSMutableArray *imageUrlArr;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) NSMutableArray <MBPhotoItemView *>*viewArr;

@property (nonatomic, assign) BOOL isCamera;

//记录失败次数 记录重试次数 6次超时
@property (nonatomic, assign) NSInteger sendTimes;

@end
@implementation MBPhotoManagerView

- (instancetype)initWithFrame:(CGRect)frame
{
    if([super initWithFrame:frame])
    {
        [self initData];
    }
    return self;
}

//如果想要判断设备是ipad，要用如下方法
- (BOOL)deviceIsIPad {
    NSString *deviceType = [UIDevice currentDevice].model;
    if([deviceType isEqualToString:@"iPad"]) {
        //iPad
        return YES;
    }
    return NO;
}

-(NSString *) getTimeNow{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    int randomNumber = arc4random_uniform(9000) + 1000;
    NSLog(@"随机数：%d", randomNumber);
    
    timeSp = [NSString stringWithFormat:@"%@%d",timeSp,randomNumber];
    
    return timeSp;
}


#pragma mark - Private Method

- (void)putUploadImage:(UIImage *)image {
    
    NSString *imageStr = @"images4";
    if (self.sendTimes % 2 == 0) {
        imageStr = @"images4";
    } else {
        imageStr = @"images5";
    }
    /**
     埋点 code
     选择相册照片上传点击事件 604
     选择拍摄上传事件 605
     */
    [[NSIOApiManager sharedManager] setIOWithCode:self.isCamera ? @"605" : @"604" content:self.isCamera ? @"USER_PROFILE_CAMERA_IMAGE_ON_CLICK" : @"USER_PROFILE_UPLOAD_IMAGE_ON_CLICK"];
    
    if (self.sendTimes == 0) {
        //只在第一次请求的发出开始通知
        [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_BEGIN object:nil];
    }
    __WeakSelf
    // Get a reference to the storage service using the default Firebase App
    FIRStorage *storage = [FIRStorage storage];

    // Create a storage reference from our storage service
    FIRStorageReference *storageRef = [storage reference];
    
    FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
    metadata.contentType = @"image/jpeg";
        
    // Data in memory
    NSData *data = UIImageJPEGRepresentation(image, 1);
//image/jpeg
    // Create a reference to the file you want to upload
    FIRStorageReference *riversRef = [storageRef child:[NSString stringWithFormat:@"%@/RegisterPhoto%@.jpg",imageStr,[self getTimeNow]]];
//    FIRStorageReference *riversRef = [storageRef child:[NSString stringWithFormat:@"images5/RegisterPhotoMebooDefult.jpg"]];

    // Upload the file to the path "images/rivers.jpg"
    [riversRef putData:data
                                                 metadata:metadata
                                               completion:^(FIRStorageMetadata *metadata,
                                                            NSError *error) {
      if (error != nil) {
        // Uh-oh, an error occurred!
//          [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_END object:nil];
          NSLog(@"%@",error);
          if (self.sendTimes >= 5) {
              [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_FAIL object:nil];
              self.sendTimes = 0;
          }  else {
              self.sendTimes++;
              [self putUploadImage:image];
          }
      } else {
          self.sendTimes = 0;
        // Metadata contains file metadata such as size, content-type, and download URL.
        int size = metadata.size;
        // You can also access to download URL after upload.
        [riversRef downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
          if (error != nil) {
            // Uh-oh, an error occurred!
//              [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_END object:nil];
              NSLog(@"%@",error);
          } else {
            NSURL *downloadURL = URL;
              NSString *urlStr = [URL absoluteString];
              NSLog(@"%@",urlStr);
              
              NSString *headerStr = @"/images";
              NSRange widthRange1 = [urlStr rangeOfString:headerStr];//匹配得到的下标
              urlStr = [urlStr substringFromIndex:widthRange1.location];
              NSRange widthRange2 = [urlStr rangeOfString:@"?"];//匹配得到的下标
              urlStr = [urlStr substringToIndex:widthRange2.location];
              NSLog(@"");
              
              
              //已有的替换,没有的加入
              if (self.index < self.imageUrlArr.count) {
                  [weakSelf.imageUrlArr replaceObjectAtIndex:self.index withObject:urlStr];
              } else {
                  [weakSelf.imageUrlArr addObject:urlStr];
              }
              if (weakSelf.photoSelectBlock) {
                  weakSelf.photoSelectBlock(weakSelf.imageUrlArr,NO);
              }
              [weakSelf preLoadImages];
              
              /**
               埋点 code
               照片上传结果事件 606
               */
              [[NSIOApiManager sharedManager] setIOWithCode:@"606" content:urlStr];
          }
        }];
      }
    }];
}

- (void)uploadImg{
    //获取
    UIAlertController  *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if ([self deviceIsIPad]){
        alert.popoverPresentationController.sourceView = self.currentViewController.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(ScreenWidth/2,ScreenHeight/2,0,0);
        alert.popoverPresentationController.permittedArrowDirections = 0;
    }
    
    UIAlertAction  *cameraAction = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isCamera = YES;
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];//读取设备授权状态
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
//            [SVProgressHUD showInfoWithStatus:RVString(@"CameraPermissions")];
        }else{
            //打开照相机
            if ([UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
                picker.delegate = self;
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self.currentViewController presentViewController:picker animated:YES completion:^{}];
            }else{

            }
        }
        
        
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"Albums" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isCamera = NO;
        //从相册中获取图片
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        [self.navigationController pushViewController:picker animated:YES];
        [self.currentViewController presentViewController:picker animated:YES completion:^{}];
    }];
    
    UIAlertAction  *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:photoAction];
    [alert  addAction:cameraAction];
    [alert addAction:cancelAction];
    [self.currentViewController presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    __WeakSelf
    MBPhotoSelectViewController *headVC = [[MBPhotoSelectViewController alloc]init];
        UIImage *editedImage = info[UIImagePickerControllerOriginalImage];
        headVC.oldImage = editedImage;
        headVC.ZHNheadImageBlock = ^(UIImage * headimage){
            [weakSelf.currentViewController dismissViewControllerAnimated:YES completion:^{
            }];
            //已有的替换,没有的加入
            if (self.index < self.imageArr.count) {
                [weakSelf.imageArr replaceObjectAtIndex:self.index withObject:headimage];
            } else {
                [weakSelf.imageArr addObject:headimage];
            }
            [weakSelf resetPhotos];
            [weakSelf putUploadImage:headimage];
        };
        [weakSelf.currentViewController.navigationController pushViewController:headVC animated:YES];

}

- (void)preLoadImages {
    for (int i = 0; i < self.imageUrlArr.count; i++) {
        NSString *urlStr = self.imageUrlArr[i];
        if (![urlStr containsString:@"http"]) {
            urlStr = [NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com%@",urlStr];
        }
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:urlStr] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        }];
    }
}

- (void)clickPhotoAction:(UITapGestureRecognizer *)TapGesture {
    self.index = TapGesture.view.tag;
    [self uploadImg];
}

- (void)resetPhotos {
    for (int i = 0 ; i < self.viewArr.count; i++) {
        MBPhotoItemView *photoView = self.viewArr[i];
        if (i < self.imageArr.count) {
            photoView.photoImageView.image = self.imageArr[i];
        } else {
            photoView.photoImageView.image = ImageWithName(@"profile_photo_back");
        }
        
        if (i > 0 && i < self.imageArr.count) {
            photoView.deleteBtn.hidden = NO;
        } else {
            photoView.deleteBtn.hidden = YES;
        }
        
        if (i == 0) {
            photoView.coverBtn.hidden = NO;
        } else {
            photoView.coverBtn.hidden = YES;
        }
    }
}

#pragma mark - UI
- (void)initData{
    self.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:0];
    
    [self addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self);
    }];
    
    for (int i = 0; i<6; i++) {
        MBPhotoItemView *photoView = [MBPhotoItemView new];
        photoView.contentMode = UIViewContentModeScaleAspectFill;
        photoView.tag  = i;
        UITapGestureRecognizer *actionTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickPhotoAction:)];
        [photoView addGestureRecognizer:actionTap];
        __WeakSelf
        photoView.deletePhotoBlock = ^{
            [weakSelf.imageArr removeObjectAtIndex:i];
            if (i < weakSelf.imageUrlArr.count) {
                [weakSelf.imageUrlArr removeObjectAtIndex:i];
            }
            
            [weakSelf resetPhotos];
            if (weakSelf.photoSelectBlock) {
                weakSelf.photoSelectBlock(weakSelf.imageUrlArr,YES);
            }
        };
        [self addSubview:photoView];
        [self.viewArr addObject:photoView];
        [photoView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (i == 0) {
                make.top.mas_equalTo(MBHeightScale(32));
                make.left.equalTo(self);
                make.width.height.mas_equalTo(2*wid+MBWidthScale(9));
            } else {
                make.width.height.mas_equalTo(wid);
                if (i<3) {
                    make.right.equalTo(self);
                    make.top.mas_equalTo(MBHeightScale(32)+(wid+MBWidthScale(9))*(i-1));
                } else {
                    make.bottom.equalTo(self);
                    make.left.mas_equalTo((wid+MBWidthScale(9))*(i-3));
                }
            }
        }];
        
        if (i < self.imageArr.count) {
            photoView.photoImageView.image = self.imageArr[i];
        } else {
            photoView.photoImageView.image = ImageWithName(@"profile_photo_back");
        }
        
        if (i > 0 && i < self.imageArr.count) {
            photoView.deleteBtn.hidden = NO;
        } else {
            photoView.deleteBtn.hidden = YES;
        }
        
        if (i == 0) {
            photoView.coverBtn.hidden = NO;
        } else {
            photoView.coverBtn.hidden = YES;
        }
    }
}

#pragma mark - Setter && Getter
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [UILabel new];
        _titleLab.text = @"My photos";
        _titleLab.textColor = HEXS(@"333333");
        _titleLab.font = PDSemiBoldScale(18);
    }
    return _titleLab;
}

- (NSMutableArray *)imageArr {
    if (!_imageArr) {
        __WeakSelf
        _imageArr = [NSMutableArray array];
        if ([MBUserAccount defaultAccount].images.count > 0) {
//            [MBProgressHUD showActivityMessageInWindow:@"Loding..."];
            for (int i = 0; i < [MBUserAccount defaultAccount].images.count; i++) {
                NSString *urlStr = self.imageUrlArr[i];
                if (![urlStr containsString:@"http"]) {
                    urlStr = [NSString stringWithFormat:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com%@",urlStr];
                }
                [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:urlStr] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                    if (image) {
                        [weakSelf.imageArr addObject:image];
                        if (weakSelf.imageArr.count == weakSelf.imageUrlArr.count) {
                            [weakSelf resetPhotos];
                        }
                        if (i == [MBUserAccount defaultAccount].images.count-1) {
//                            [MBProgressHUD hideHUD];
                        }
                    }
                }];
            }
        }
    }
    return _imageArr;
}

- (NSMutableArray *)imageUrlArr {
    if (!_imageUrlArr) {
        _imageUrlArr = [NSMutableArray array];
        if ([MBUserAccount defaultAccount].images) {
            _imageUrlArr = [MBUserAccount defaultAccount].images;
        }
    }
    return _imageUrlArr;
}

- (NSMutableArray<MBPhotoItemView *> *)viewArr {
    if (!_viewArr) {
        _viewArr = [NSMutableArray array];
    }
    return _viewArr;
}

@end
